package cn.itcast.tlias.com.tliaswork.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

@Component
public class AliOSSUtils {

    //OSS文件目录
    private String folder = "img/";

    @Autowired
    private AliOSSUtilsProperties mProperties;
    public String uploadFile(MultipartFile file) {

         String endpoint =mProperties.getEndpoint();
         String accessKeyId=mProperties.getAccessKeyId();
         String accessKeySecret=mProperties.getAccessKeySecret();
         String bucketName=mProperties.getAbucketName();
         OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //上传文件名
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        filename = uuid + filename;

        PutObjectRequest putObjectRequest = null;

        // 添加 ContentType
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");
        try {
            putObjectRequest = new PutObjectRequest(bucketName, folder + filename, new ByteArrayInputStream(file.getBytes()), objectMetadata);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();

        return "https://" + bucketName + "." + endpoint + "/" + folder + filename;
    }
}
